<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\11 0011
 * Time: 17:01
 */

namespace app\Lib\Model\AdminAuth\AdminMenu;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\AdminAuth\AdminMenu\EditAdminMenuHandle;
use app\Lib\InterfaceIn\AdminAuth\MenuAuthHandle;

class EditAdminMenu extends AdminMenuBase implements EditAdminMenuHandle
{
    /** @var MenuAuthHandle $menuAuth */
    private $menuAuth;
    /**
     * 要修改的菜单类
     * @param MenuAuthHandle $menuAuth
     * @return $this
     */
    public function setMenuAuth(MenuAuthHandle $menuAuth)
    {
        $this->menuAuth = $menuAuth;
        return $this;
    }

    /**
     * 参数验证和数据整合
     * @return array
     * @throws BlException
     */
    private function check(){
        if(!$this->menuAuth instanceof  MenuAuthHandle){
            throw new BlException('请先实例化菜单权限类');
        }
        $model  = $this->getMenuDb();
        $data   =  $this->handleArray();
        $data[$model->_save_uid ]  = $this->opUser->getUid();
        $data[$model->_save_time]  = time();
        $data[$model->_id]         = $this->menuAuth->getMenuId();
        if(!$this->getValidate()->scene('save')->check($data)){
            throw new BlException($this->getValidate()->getError());
        }
        return $data;
    }

    /**
     * 修改菜单
     * @return bool
     * @throws BlException
     */
    public function run()
    {
        $data    =  $this->check();
        $model   =  $this->getMenuDb();
        $result  =  $model->update($data);
        if(!$result){
            throw new BlException('操作失败');
        }
        $this->menuAuth->delAllCache();
        return true;
    }

}